import requests
from datetime import datetime, timedelta
import json
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point

def fetch_data(start_time, end_time, time_delta_label):
    base_url = "https://sqfb.slt.zj.gov.cn/rest/newList/getNewTotalRainList"
    params = {
        "areaFlag": "1",
        "sss": "衢州市",
        "ssx": "",
        "st": start_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "et": end_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "ly": "",
        "max": "",
        "min": "0",
        "bool": "false",
        "bxdj": "1,2,3,4,5,",
        "zm": "",
        "type": "0",
        "lx": "QX,ME,SX,DS"
    }

    headers = {
        "User-Agent": "Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14"
    }

    response = requests.get(base_url, params=params, headers=headers,verify=False)
    response.encoding = "utf-8"

    data = json.loads(response.text)

    merged_list = [value for value_list in data.values() for value in value_list]

    data1 = []
    for line in merged_list:
        data1.append(line)

    df = pd.DataFrame(data1)
    df['时间段'] = [time_delta_label] * len(df)

    return df

def fetch_monthly_data(year, month):
    start_date = datetime(year, month, 1)
    next_month = start_date.replace(day=28) + timedelta(days=4)
    end_date = next_month - timedelta(days=next_month.day)
    
    all_data = pd.DataFrame()

    current_date = start_date
    while current_date <= end_date:
        next_date = current_date + timedelta(days=1)
        df = fetch_data(current_date, next_date, current_date.strftime("%Y-%m-%d"))
        all_data = pd.concat([all_data, df], ignore_index=True)
        current_date = next_date
    
    return all_data

year = 2023
month = 1

monthly_data = fetch_monthly_data(year, month)

pivoted_data = monthly_data.pivot_table(
    index=['zm', 'jd', 'wd'],
    columns='时间段',
    values='yl',
    aggfunc='first'
).reset_index()

x_values = pivoted_data["jd"]
y_values = pivoted_data["wd"]

geometry = [Point(xy) for xy in zip(x_values, y_values)]
gdf = gpd.GeoDataFrame(pivoted_data, geometry=geometry)
gdf.set_crs(epsg=4326, inplace=True)

excel_file = r"G:\2023工作\suan\monthly_result.xlsx"
pivoted_data.to_excel(excel_file, sheet_name="雨量", startcol=0, index=False)

#gdb_path = r"F:\2023工作\suan\monthly_result.gdb"
#gdf.to_file(gdb_path, driver='FileGDB', encoding='utf-8')

print("每月每日数据合并输出完毕")
